package cn.iocoder.yudao.framework.common.config;

import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;

@AutoConfiguration
@Slf4j
public class YudaoCommonAutoConfiguration {

    @Value("${spring.jackson.time-format:HH:mm:ss}")
    private String timeFormat;

    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String dateFormat;


    @Bean
    Jackson2ObjectMapperBuilderCustomizer customizeLocalDateTimeFormat() {

        return jacksonObjectMapperBuilder -> {

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
            jacksonObjectMapperBuilder.dateFormat(simpleDateFormat);

            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dateFormat);
            jacksonObjectMapperBuilder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter));
            jacksonObjectMapperBuilder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter));

            DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern(timeFormat);
            jacksonObjectMapperBuilder.serializerByType(LocalTime.class, new LocalTimeSerializer(timeFormatter));
            jacksonObjectMapperBuilder.deserializerByType(LocalTime.class, new LocalTimeDeserializer(timeFormatter));

            //jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringSerializer.instance);

            jacksonObjectMapperBuilder.timeZone(TimeZone.getDefault());
        };
    }

    @Bean
    public JsonUtils initJsonUtils(ObjectMapper objectMapper) {
        JsonUtils.init(objectMapper);
        return null;
    }

}

